
import 'package:banyou_app/app/widget/app_bar_widget.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../controllers/script_controller.dart';
import 'package:webview_flutter/webview_flutter.dart' as webv;
import 'package:webview_flutter/webview_flutter.dart';

class ScriptView extends GetView<ScriptController> {
  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          appBar: AppBarWidget(
              showLeading: controller.canGoBack.value,
              leadingCallback: () async {
                if (controller.webViewController != null) {
                  bool a = await controller.webViewController!.canGoBack();
                  if (a) {
                    controller.webViewController!.goBack();
                  } else {
                    controller.webViewController!.reload();
                  }
                }
              },
              titleStr: controller.title.value),
          body: web(),
        ));
  }

  Future<bool> _exitApp(BuildContext context) async {
    if (controller.webViewController != null &&
        await controller.webViewController!.canGoBack()) {
      // 查看  history 有没有可以返回的  如果有  则返回 history
      print("onwill goback");
      print("进来里唯一返回的");
      controller.webViewController!.goBack(); // history 返回
      return Future.value(false);
    } else {
      print("这里history没有返回的");
      debugPrint("_exit will not go back");
      return Future.value(true);
    }
  }

  web() {
    return Obx(() => controller.url.value.length > 0
        ? webv.WebView(
            initialUrl: controller.url.value, //需要打开的url

            //是否支持js 默认是不支持的，
            javascriptMode: webv.JavascriptMode.unrestricted,
            gestureNavigationEnabled: true,
            //加载js方法到页面内，js通过此来调用flutter的方法
            javascriptChannels: _loadJavascriptChannel(),
            //路由委托（可以通过在此处拦截url实现JS调用Flutter部分）
            navigationDelegate: (NavigationRequest request) {
              if (request.url.startsWith('servicef')) {
                // Bridge.preventUrl(request.url, _controller);
                Uri service = Uri.parse(request.url);
                Map q = service.queryParameters;
                if (q.isNotEmpty && q.containsKey('url')) {
                  controller.launchURL(Uri.parse(q['url']));
                }
                return NavigationDecision.prevent;
              }

              return NavigationDecision.navigate;
            },

            onWebViewCreated: (web) {
              controller.webViewController = web;
            },
            onProgress: (progress) async {
              print('object');
              print(progress);
              bool a = await controller.webViewController!.canGoBack();
              print(a);
            },
            onWebResourceError: (error) {
              print('加载失败');
              print(error);
            },

            onPageFinished: (url) async {
              String title = await controller.webViewController!
                  .runJavascriptReturningResult('document.title');
              print('title=======' + title);
              controller.canGoBack.value =
                  await controller.webViewController!.canGoBack();
              // String currentUrl =
              //     await controller.webViewController!.currentUrl() ?? "";
              // controller.canGoBack.value = currentUrl == controller.url.value;
              // print('canGoBack=======' + controller.canGoBack.value.toString());
              // print('currentUrl=======' + currentUrl);

              // controller.title.value = title.length == 0 ? '直约' : title;
            },
          )
        : Container());
  }

  /// 获取当前加载页面的 title
  _getTitle() async {
    String title = await controller.webViewController!.getTitle() ?? "";

    print("title---$title");
    // controller.title.value = title;
  }

  Set<JavascriptChannel> _loadJavascriptChannel() {
    final Set<JavascriptChannel> channels = Set<JavascriptChannel>();
    JavascriptChannel startFunction = JavascriptChannel(
        name: 'startFunction',
        onMessageReceived: (JavascriptMessage message) {
          // _getTitle();

          controller.messageHandle(message);
          // print(jsonDecode(message.message));
        });
    // JavascriptChannel h5JumpNative = JavascriptChannel(
    //     name: 'h5JumpNative',
    //     onMessageReceived: (JavascriptMessage message) {
    //       print('获取到方法');
    //       print(message.message);
    //     });
    // JavascriptChannel appJump = JavascriptChannel(
    //     name: 'appJump',
    //     onMessageReceived: (JavascriptMessage message) {
    //       print('获取到方法');
    //       print(message.message);
    //     });

    channels.addAll([
      startFunction,
    ]);
    return channels;
  }
}
